<script setup>
import Loader from "@/components/Loader.vue";
import {ref} from "vue";
import request from "@/assets/request.js";

const files = ref([])
const showLoader = ref(true)

const getFiles = async () => {
  const response =  await request('shared', 'GET', null, true)
  if (response.status === 200) {
    files.value = response.message
    console.log(response.message)
    showLoader.value = false
  }
  if (response.status === 403 && response.message.message === "Forbidden for you") {
    store.methods.exit(router)
  }
}

const downloadFile = async (id, name) => {
  const response = await request(`files/${id}`, 'GET', null, true, true)
  let blob = await response.blob()
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = name
  a.click()

  window.URL.revokeObjectURL(blob)
}


getFiles()
</script>

<template>
<div class="container-start">
    <h2>Файлы доступные пользователю</h2>

    <transition-group name="grid" tag="div" class="grid-files">
      <div class="file-card" v-for="file in files" :key="file.file_id" >
        <span class="files-info"><span class="files-info-title">Имя файла: </span>{{ file.name }}</span>
        <span class="files-info"><span class="files-info-title">ID файла: </span>{{ file.file_id }}</span>
        <div class="file-buttons">
          <button class="download" @click="downloadFile(file.file_id, file.name)">Скачать</button>
        </div>
      </div>
    </transition-group>
  <Loader :show="showLoader"></Loader>
</div>
</template>

<style scoped>
    .grid-files {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
    gap: 50px;
    width: 100%;
  }

  .file-card {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 20px;
    background: #2c3e50;
    border: 3px #2c3e50 solid;
    border-radius: 16px;
    transition: all .25s ease-in-out;
  }

  .file-card:hover {
    border: 3px #42b883 solid;
    box-shadow: 0px 0px 7px 3px #42b883;
  }

  .files-info {
    font-size: 16px;
  }

  .files-info-title {
    color: white;
  }

  .file-buttons {
    display: grid;
    grid-template-columns: 1fr;
    width: 100%;
    gap: 10px;
  }

  button {
    padding: 10px 12px;
    background: #282828;
    color: white;
    outline: none;
    border: #282828 2px solid;
    font-size: 16px;
    border-radius: 8px;
    transition: all .5s;
  }

  .download:hover {
    box-shadow: 0px 0px 7px 3px #00f665;
    border: #00f665 2px solid;
  }

  .grid-enter, .grid-leave-to {
    opacity: 0;
  }

  .grid-leave-active {
    position: absolute;
  }

</style>